package com.i_art_engineer.meigong.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.i_art_engineer.meigong.AppConsts;
import com.i_art_engineer.meigong.AppContext;
import com.i_art_engineer.meigong.AppHttpClient;
import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.base.ActionBarActivity;
import com.i_art_engineer.meigong.util.CacheUtils;
import com.i_art_engineer.meigong.util.StringUtils;
import com.i_art_engineer.meigong.widget.AvatarImageView;
import com.i_art_engineer.meigong.widget.InputDialog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;

/**
 * 个人中心界面
 */
public class AccountActivity extends ActionBarActivity {

    private AvatarImageView avatarImageView;
    private LinearLayout ll_phrases, ll_feedback, ll_share, ll_clear, ll_logout, ll_about;
    private TextView tv_userName;
    private Button btn_userName;
    private View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.item_cant:
                    startActivity(new Intent(AccountActivity.this, CantActivity.class));
                    break;
                case R.id.item_feedback:
                    startActivity(new Intent(AccountActivity.this, FeedbackActivity.class));
                    break;
                case R.id.item_share:
                    shareMsg("i美工", "绝佳软件", "i美工是个好软件，下载地址：http://#", null);
                    break;
                case R.id.item_clear_cache:
                    Toast.makeText(AccountActivity.this, "开始清理缓存文件！", Toast.LENGTH_SHORT).show();
                    int i = CacheUtils.cleanInternalCache(AccountActivity.this);
                    Toast.makeText(AccountActivity.this, "总共清理了" + i + "个文件！", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.item_logout:
                    getApplicationContext().sendBroadcast(new Intent("finish"));
                    Intent intent = new Intent(AccountActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    AppContext.cleanTicket();
                    startActivity(intent);
                    finish();
                    break;
                case R.id.item_about:
                    startActivity(new Intent(AccountActivity.this, AboutActivity.class));
                    break;
                case R.id.btn_username:
                    showTextInputDialog();
                    break;
            }
        }
    };

    public void showTextInputDialog() {
        String input = "请输入昵称";
        new InputDialog(AccountActivity.this).builder().setMsg(input).setPositiveButton(
                getString(R.string.btn_ok),
                new InputDialog.OnInputClickListener() {
                    @Override
                    public void onClick(String v) {
                        tv_userName.setText(v);

                        SharedPreferences preferences = AppContext.getPersistPreferences();
                        preferences.edit().putString("username", v).commit();
                        syncName();
                    }
                }).setNegativeButton("取消", null).show();
    }

    private void syncAvatar(File avatar) {
        Log.i("loadProfile", AppContext.getTicket());
        AsyncHttpResponseHandler jhandler = new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    Log.i("syncAvatar", response.toString());
                    int code = response.getInt("code");
                    String msg = response.getString("msg");

                    Log.i("syncAvatar-msg", msg);
                    if (code == 200) {
                        String avatarpath = response.getString("data");
                        SharedPreferences preferences = AppContext.getPersistPreferences();
                        preferences.edit().putString("avatarpath", avatarpath).commit();
                        Toast.makeText(AccountActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.i("syncAvatar", responseString);
            }
        };
        RequestParams params = new RequestParams();
        try {
            params.put("avatar", avatar);
        } catch (Exception e) {
            e.printStackTrace();
        }
        AppHttpClient.post(AppConsts.API_PROFILE_AVATAR, params, jhandler);
    }

    private void syncName() {
        AsyncHttpResponseHandler jhandler = new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    Log.i("syncName", response.toString());
                    int code = response.getInt("code");
                    String msg = response.getString("msg");

                    Log.i("syncName-msg", msg);
                    Toast.makeText(AccountActivity.this, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.i("syncName", responseString);
            }
        };
        RequestParams params = new RequestParams();
        params.put("name", tv_userName.getText().toString());
        AppHttpClient.post(AppConsts.API_PROFILE_UPDATE, params, jhandler);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);

        String token = AppContext.getTicket();
        if (token == null) {
            finish();
        }
        initActionBar(R.string.title_personal);

        avatarImageView = (AvatarImageView) findViewById(R.id.ivAvatar);
        FileInputStream fis = null;
        try {
            fis = openFileInput("avatar.png");
            if (fis != null) {
                Bitmap avaterphoto = BitmapFactory.decodeStream(fis);
                avatarImageView.setImageBitmap(avaterphoto);
                fis.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        avatarImageView.setAfterCropListener(new AvatarImageView.AfterCropListener() {
            @Override
            public boolean afterCrop(Bitmap photo) {
                Toast.makeText(AccountActivity.this, "设置新的头像成功", Toast.LENGTH_SHORT).show();
                FileOutputStream outStream = null;
                try {
                    outStream = AccountActivity.this.openFileOutput("avatar.png", Context.MODE_PRIVATE);
                    photo.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                File path = getFileStreamPath("avatar.png");
                syncAvatar(path);
                return true;
            }


        });

        ll_phrases = (LinearLayout) findViewById(R.id.item_cant);
        ll_feedback = (LinearLayout) findViewById(R.id.item_feedback);
        ll_share = (LinearLayout) findViewById(R.id.item_share);
        ll_clear = (LinearLayout) findViewById(R.id.item_clear_cache);
        ll_logout = (LinearLayout) findViewById(R.id.item_logout);
        ll_about = (LinearLayout) findViewById(R.id.item_about);

        ll_phrases.setOnClickListener(listener);
        ll_feedback.setOnClickListener(listener);
        ll_share.setOnClickListener(listener);
        ll_clear.setOnClickListener(listener);
        ll_logout.setOnClickListener(listener);
        ll_about.setOnClickListener(listener);

        tv_userName = (TextView) findViewById(R.id.tv_username);
        btn_userName = (Button) findViewById(R.id.btn_username);
        btn_userName.setOnClickListener(listener);
        loadProfile();
    }

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    try {
                        Bundle bundle = msg.getData();
                        String name = bundle.getString("name");
                        String avatar = bundle.getString("avatar");
                        tv_userName.setText(name);
                        avatar = "";
                        //       loadImage(avatar);
                        Drawable drawable = Drawable.createFromStream(new URL(avatar).openStream(), "image.png");
                        avatarImageView.setImageDrawable(drawable);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    Drawable drawable = (Drawable) msg.obj;
                    avatarImageView.setImageDrawable(drawable);
                    break;
            }


        }
    };

    void loadImage(final String url) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Drawable drawable = null;
                try {
                    drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Message message = new Message();
                message.obj = drawable;
                message.what = 2;//daibiao na tupian
                handler.sendMessage(message);
            }
        };
        thread.start();
    }

    private void loadProfile() {
        /**
         * profile/info
         {"code":200,"msg":"","data":{"id":"Bz2KDmEY","name":"哈哈","avatar":"http:\/\/www.9fanr.com\/"}}
         */
        Log.i("loadProfile", AppContext.getTicket());
        AsyncHttpResponseHandler jhandler = new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    Log.i("loadProfile", response.toString());
                    int code = response.getInt("code");
                    String msg = response.getString("msg");

                    Log.i("loadProfile-msg", msg);
                    if (code == 200) {
                        JSONObject jobj = response.getJSONObject("data");
                        String name = jobj.getString("name");
                        String avatar = jobj.getString("avatar");
                        Bundle bundle = new Bundle();
                        bundle.putString("name", name);
                        bundle.putString("avatar", avatar);
                        tv_userName.setText(name);
                        if (!StringUtils.isEmpty(avatar))
                            loadImage(avatar);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.i("loadProfile", responseString);
            }
        };
        AppHttpClient.post(AppConsts.API_PROFILE_INFO, jhandler);
    }

    /**
     * 分享功能
     *
     * @param activityTitle Activity的名字
     * @param msgTitle      消息标题
     * @param msgText       消息内容
     * @param imgPath       图片路径，不分享图片则传null
     */
    public void shareMsg(String activityTitle, String msgTitle, String msgText, String imgPath) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (imgPath == null || imgPath.equals("")) {
            intent.setType("text/plain"); // 纯文本
        } else {
            File f = new File(imgPath);
            if (f != null && f.exists() && f.isFile()) {
                intent.setType("image/jpg");
                Uri u = Uri.fromFile(f);
                intent.putExtra(Intent.EXTRA_STREAM, u);
            }
        }
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(Intent.createChooser(intent, activityTitle));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //在拍照、选取照片、裁剪Activity结束后，调用的方法
        if (avatarImageView != null) {
            avatarImageView.onActivityResult(requestCode, resultCode, data);
        }
    }

}
